package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.dao.OrderDao;
import com.itheima.domain.*;
import com.itheima.dto.OrdersDto;
import com.itheima.exception.CustomException;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        if(shoppingCartList==null||shoppingCartList.isEmpty()){
            throw new CustomException("购物车为空，不能下单");
        }

        //根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);

        //根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        long orderId = IdWorker.getId();//订单号
        AtomicInteger amount = new AtomicInteger(0);
        //组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        //组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);
        //想订单明细表保存多条数据
        orderDetailService.saveBatch(orderDetails);
        //删除当前用户的购物车列表数据
        shoppingCartService.remove(lqw);
    }

    @Override
    public Page<OrdersDto> orderPage(Integer page, Integer pageSize) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getCheckoutTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //条件查询后的页码封装对象
        Page<Orders> page1 = this.page(ordersPage, wrapper);
        //创建一个泛型是dto的页码对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        List<Orders> ordersList = page1.getRecords();
        //创建dto集合
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            Long ordersId = orders.getId();
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> list = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(list);
            ordersDtoList.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtoList);
        ordersDtoPage.setTotal(ordersPage.getTotal());
        return ordersDtoPage;
    }

    @Override
    public Page<OrdersDto> findByPage(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //判断订单号和时间是否为空
        wrapper.like(number!=null, Orders::getId,number);
        if(beginTime!=null||endTime!=null){
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        Page<Orders> page1 = page(ordersPage, wrapper);
        //创建一个泛型是dto的页码对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        List<Orders> ordersList = page1.getRecords();
        //创建dto集合
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            Long ordersId = orders.getId();
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> list = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(list);
            ordersDtoList.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtoList);
        ordersDtoPage.setTotal(ordersPage.getTotal());

        return ordersDtoPage;
    }

    @Override
    public void again(OrdersDto ordersDto) {
        System.out.println(ordersDto);
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,ordersDto.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(lqw);

        orderDetails.stream().forEach(c->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setNumber(c.getNumber());
            shoppingCart.setName(c.getName());
            shoppingCart.setAmount(c.getAmount());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setImage(c.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setDishId(c.getDishId());
            shoppingCart.setDishFlavor(c.getDishFlavor());
            shoppingCart.setSetmealId(c.getSetmealId());
            shoppingCartService.add(shoppingCart);
            //cartList.add(shoppingCart);
        });
        //shoppingCartService.saveBatch(cartList);
    }
}